import axios from 'axios'
import store from '@/store'
import {ElMessage, ElMessageBox} from 'element-plus'
import myLoading from '@/utils/myLoading'
import router from '@/router'

//创建axios对象
const http = axios.create({
  //baseURL: 'http://localhost:8080/',
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  withCredentials: false
})

/**
 * loading成员
 * 当config.loading为true时，加载myLoading.start服务
 */
let loading

/**
 * 请求拦截器
 */
http.interceptors.request.use(config => {
  if (config.loading) {
    loading = myLoading.start()
  }

  if (store.state.token !== null) {
    config.headers.authorization = store.state.token
  }
  return Promise.resolve(config)
}, error => {
  if (loading !== undefined) {
    myLoading.close()
  }
  ElMessage.error('网络异常')
  return Promise.reject(error)
})

/**
 * 响应拦截器
 */
http.interceptors.response.use(response => {
  if (loading !== undefined) {
    loading.close()
  }
  return Promise.resolve(response)
}, error => {
  if (loading !== undefined) {
    loading.close()
  }
  switch (error.response.status) {
    case 500:
      ElMessage.error('请求失败: 后端服务器错误')
      break
    case 405:
      ElMessage.error('请求失败: 请求方式不正确')
      break
    case 404:
      ElMessage.error('请求失败: 请求的资源不存在')
      break
    case 401:
      store.commit('token', {token: null})
      ElMessageBox.alert('您的登陆状态已失效，请重新登陆', '提示', {
        showClose: false,
        callback: () => {
          router.push({name: 'Login'}).then(r => {
            console.log('why?')
          })
        }
      }).then(r => {
        console.log('why i wrote it like this?')
      })
      break
    default:
      ElMessage.error(error.message)
      break
  }
  return Promise.reject(error)
})

export default http